<template>
  <a-card>
    <a-form ref="ruleForm" :form="form" v-bind="layout">
      <a-row>
        <a-col :md="8" :sm="24">
          <a-form-item label="存货名称" style="margin-bottom: 0">
            <a-select
              mode="multiple"
              v-model="form.inventoryName"
              allowClear
              @search="handleSearch"
              @change="inventoryNameChange"
              showSearch
            >
              <a-select-option
                v-for="val in stockCodeList"
                :key="val.id"
                :value="
                  val.invcode +
                  '|' +
                  val.inventoryName +
                  '|' +
                  val.invspec +
                  '|' +
                  val.unit +
                  '|' +
                  val.pkInvbasdoc
                "
              >
                {{ val.invcode }} {{ val.inventoryName }}{{ val.invspec }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="24">
          <a-form-model-item label="业务日期">
            <a-range-picker v-model="form.BusinessDate" />
          </a-form-model-item>
        </a-col>
        <a-col :md="8" :sm="24">
          <a-form-item
            ref="danjuzhuangtai"
            label="单据状态"
            prop="danjuzhuangtai"
          >
            <a-select v-model="form.auditMark">
              <a-select-option
                v-for="(item, index) in danjuzhuangtailist"
                :value="item.value"
                :key="index"
              >
                {{ item.title }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="24">
          <a-form-item style="margin-bottom: 0" label="仓库名称">
            <a-select style="width: 100%" v-model="form.pkStordoc">
              <a-select-option
                v-for="item in WarehouseCodeList"
                :key="item.depotId"
                :value="
                  item.depotNo + '|' + item.depotName + '|' + item.pkStordoc
                "
                >{{ item.depotNo }} {{ item.depotName }}</a-select-option
              >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="24">
          <a-form-model-item label="会计期间">
            <a-range-picker
              format="YYYY-MM"
              v-model="form.accountingPeriodDate"
            />
          </a-form-model-item>
        </a-col>
        <a-col :md="8" :sm="24">
          <a-form-model-item label="收发标志">
            <a-select
              style="width: 300px; margin-left: 5px"
              v-model="form.inboundOutboundIdentification_dirtext"
              @change="inboundOutboundIdentificationHandleChange"
              showSearch
            >
              <a-select-option value="1"> 收类型 </a-select-option>
              <a-select-option value="2"> 发类型 </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>

        <a-col :span="24" :style="{ textAlign: 'right' }">
          <!-- chaxun -->
          <a-button type="primary" @click="onSubmit">查询</a-button>
          <a-button style="margin-left: 8px" @click="reset">重置</a-button>
          <a-button
            style="margin-left: 8px"
            type="primary"
            @click="exportToExcel"
            >导出</a-button
          >
        </a-col>
      </a-row>
    </a-form>
    <br />
    <a-table
      :columns="columns"
      :data-source="dataSource"
      :pagination="pagination"
      :scroll="{ x: 3000, y: 670 }"
      @change="handleTableChange"
      size="small"
    >
    </a-table>
  </a-card>
</template>

<script>
// ------- 公共接口 ------- ;
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax();
import moment from "moment";
import { liushuizhangHttp } from "@/services/modules/ZhangBuChaXun/ChuRuKuLiuShuiZhang";
const $http = new liushuizhangHttp();
import { ZiDianBiaoHttp } from "@/services/modules/ZiDianBiao";
const $zidianhttp = new ZiDianBiaoHttp();
import XLSX from "xlsx";
import { sheet2blob } from "@/utils/export.js";
import FileSaver from "file-saver";
const columns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
  },
  {
    title: "会计期间",
    align: "center",
    dataIndex: "accountingPeriodDate",
  },
  {
    title: "业务日期",
    align: "center",
    dataIndex: "BusinessDate",
  },
  {
    title: "单据号",
    align: "center",
    width: "8%",
    dataIndex: "document",
  },
  {
    title: "收发类别",
    align: "center",
    dataIndex: "sendReceiveType",
  },
  {
    title: "仓库名称",
    align: "center",
    width: "5%",
    dataIndex: "pkStordoc",
  },
  {
    title: "存货编码",
    align: "center",
    dataIndex: "inventoryNo",
    width: "8%",
  },
  {
    title: "存货名称",
    align: "center",
    dataIndex: "inventoryName",
    width: "8%",
  },
  {
    title: "规格型号",
    align: "center",
    dataIndex: "specificationsModel",
    width: "8%",
  },
  {
    title: "单位",
    align: "center",
    dataIndex: "unit",
  },
  {
    title: "入库单价",
    align: "center",
    dataIndex: "ruunitPrice",
  },
  {
    title: "入库数量",
    align: "center",
    dataIndex: "ruquantity",
  },
  {
    title: "入库金额",
    align: "center",
    dataIndex: "rumoney",
  },
  {
    title: "出库单价",
    align: "center",
    dataIndex: "chuunitPrice",
  },
  {
    title: "出库数量",
    align: "center",
    dataIndex: "chuquantity",
  },
  {
    title: "出库金额",
    align: "center",
    dataIndex: "chumoney",
  },
  {
    title: "客户",
    align: "center",
    dataIndex: "clientId",
  },
  {
    title: "供应商",
    align: "center",
    dataIndex: "supplier",
    width: "8%",
  },
  {
    title: "源单号",
    align: "center",
    width: "5%",
    dataIndex: "sourceNumber",
  },
  {
    title: "产成品分类",
    align: "center",
    dataIndex: "finishedProductType",
  },
  {
    title: "产成品仓库",
    align: "center",
    dataIndex: "finishedProductDepot",
  },
  {
    title: "备注",
    align: "center",
    dataIndex: "remark",
  },
  {
    title: "制单人",
    align: "center",
    dataIndex: "singleProducer",
  },
  {
    title: "审核人",
    align: "center",
    dataIndex: "inspector",
  },
];
export default {
  data() {
    return {
      pagination: {
        total: 0,
        current: 1,
        pageSize: 10, //每页中显示10条数据
        pageSizeOptions: ["10"], //每页中显示的数据
        showTotal: (total) => `共有${total}条数据`, //分页中显示总的数据
      },
      columns,
      layout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 18 },
      },
      WarehouseCodeList: [],
      stockCodeList: [], //存货名称
      danjuzhuangtailist: [], //单据状态
      shoufaleibielist: [], //收发类别
      danjuleixinglist: [], //单据类型
      form: {
        inventoryNo: [],
        BusinessDate: [],
        inventoryName: [],
        auditMark: "",
        pkStordoc: "",
        accountingPeriodDate: [],
        inboundOutboundIdentification: "",
        inboundOutboundIdentification_dirtext: "",
      },
      dataSource: [],
      queryPathChache: "",
    };
  },
  mounted() {
    this.getlist(); //获取出入库流水list
    this.getApplyStorage(); //获取仓库名称

    this.getAuditMarkAndDocumentStatus(); //单据状态
  },
  methods: {
    /**
    //todo @description: 导出功能
    * @description: ...
    * @return
    */
    exportToExcel() {
      this.showSpin = true; //打印加载中
      $http
        .getliushuizhang(
          "?pageNo=1&pageSize=" + this.maxSize + this.queryPathChache
        )
        .then((res) => {
          console.log("导入的数据", res.result.records);
          let array = res.result.records;
          this.exportBasic(array);
        });
    },
    //  接收数组，进行导出
    exportBasic(Array) {
      console.log("要导出的数据为:::::", Array);
      //  规整要导出的数据:::::
      let array = [];
      for (let i = 0; i < Array.length; i++) {
        let data = {
          序号: i + 1,
          会计期间: Array[i].accountingPeriodDate,
          业务日期: Array[i].businessDate,
          单据号: Array[i].document,
          收发类别: Array[i].sendReceiveType,
          仓库名称: Array[i].storname,
          存货编码: Array[i].invcode,
          存货名称: Array[i].invname,
          规格型号: Array[i].invspec,
          单位: Array[i].measname,
          入库单价: Array[i].inUnitPrice,
          入库数量: Array[i].inQuantity,
          入库金额: Array[i].inMoney,
          出库单价: Array[i].outUnitPrice,
          出库数量: Array[i].outQuantity,
          客户: Array[i].customerName,
          供应商: Array[i].supplier,
          源单号: Array[i].sourceNumber,
          产成品分类: Array[i].finishedProductType_dictText,
          产成品仓库: Array[i].finishedProductDepot_dictText,
          备注: Array[i].remark,
          制单人: Array[i].singleProducer_dictText,
          审核人: Array[i].inspector_dictText,
        };
        array.push(data);
      }
      // 生成 sheet 表格 数据
      let sheet = XLSX.utils.json_to_sheet(array, {
        // 对导出内容进行相应的排序,手动排序。
        header: [
          "序号",
          "会计期间",
          "业务日期",
          "单据号",
          "收发类别",
          "仓库名称",
          "存货编码",
          "存货名称",
          "规格型号",
          "单位",
          "入库单价",
          "入库数量",
          "入库金额",
          "出库单价",
          "出库数量",
          "客户",
          "供应商",
          "源单号",
          "产成品分类",
          "产成品仓库",
          "备注",
          "制单人",
          "审核人",
        ],
      });
      // 生成导出表格
      let blob = sheet2blob(sheet);
      try {
        FileSaver.saveAs(
          new Blob([blob], {
            type: "application/octet-stream",
          }),
          "出入库流水账.xlsx" // 导出文件夹名称
        );
      } catch (e) {
        console.log(e);
      }
      this.showSpin = false; //导出中
    },
    handleSearch(value) {
      //模糊查询
      this.stockCodeList = [];
      console.log("value", value);
      let query = "?name=" + value;
      console.log("query", query);
      if (value == "" || value == null) {
        this.stockCodeList = [];
      } else {
        comHttp.getgetSearchInventoryInformationFile(query).then((res) => {
          console.log("结果为", res);
          // this.goodsList = res.result;
          for (let i = 0; i < res.result.length; i++) {
            if (
              res.result[i].specificationsModel == "null" ||
              res.result[i].specificationsModel == null
            ) {
              res.result[i].specificationsModel = "";
            }
            if (res.result[i].unit == "null" || res.result[i].unit == null) {
              res.result[i].unit = "";
            }
            let data = {
              key: i,
              inventoryId: res.result[i].id, // 存货 id
              invcode: res.result[i].invcode, //存货编码
              inventoryName: res.result[i].invname, //存货名称
              invspec: res.result[i].invspec, //规格型号
              unit: res.result[i].unit, //单位
              pkInvbasdoc: res.result[i].pkInvbasdoc,
            };
            this.stockCodeList.push(data);
          }
        });
      }
    },
    // 搜索栏选择存货编码编码的change触发函数
    inventoryNameChange(value, option) {
      console.log(value, option);
      this.form.id = option.key;
      // console.log(value , option);

      // const newValue = value.split("|");
      // console.log("搜索栏选择了存货编码", newValue);
      this.form.invcode = value.split("|")[4]; // 存货名称主键
      // this.form.inventoryName = newValue[1];
      // this.form.inventoryInformationId = newValue[2];
    },
    inboundOutboundIdentificationHandleChange(value, options) {
      console.log(options);
      this.form.inboundOutboundIdentification = value;
      this.form.inboundOutboundIdentification_dirtext =
        options.componentOptions.children[0].text;
    },

    onSubmit() {
      this.pagination = {
        total: 0,
        current: 1,
        pageSize: 10, //每页中显示10条数据
        pageSizeOptions: ["10"], //每页中显示的数据
        showTotal: (total) => `共有${total}条数据`, //分页中显示总的数据
      };
     
      let form = this.form;
      console.log(form);
      let queryPathChache = "";

      // 存货名称 pkInvbasdoc
      if (form.inventoryName.length > 0) {
        let res = form.inventoryName
          .map((item) => {
            return item.split("|")[4];
          })
          .join(",");
        queryPathChache += `&pkInvbasdoc=${res}`;
      }
      // 业务日期
      if (form.BusinessDate.length > 0) {
        queryPathChache += `&beginDate=${moment(form.BusinessDate[0]).format(
          "YYYY-MM-DD"
        )}`;
        queryPathChache += `&endDate=${moment(form.BusinessDate[1]).format(
          "YYYY-MM-DD"
        )}`;
      }

      // 单据状态
      if (form.auditMark) {
        if (form.auditMark !== "3") {
          queryPathChache += `&auditMark=${form.auditMark}`;
        }
      }
      // 仓库名称
      if (form.pkStordoc) {
        queryPathChache += `&pkStordoc=${form.pkStordoc.split("|")[2]}`;
      }
      // 会计期间
      if (form.accountingPeriodDate.length > 0) {
        queryPathChache += `&accountingPeriodBegin=${moment(
          form.accountingPeriodDate[0]
        ).format("YYYY-MM")}`;
        queryPathChache += `&accountingPeriodEnd=${moment(
          form.accountingPeriodDate[1]
        ).format("YYYY-MM")}`;
      }

      // 收发标志
      if (form.inboundOutboundIdentification) {
        queryPathChache += `&inboundOutboundIdentification=${form.inboundOutboundIdentification}`;
      }

      console.log(queryPathChache);

      this.queryPathChache = queryPathChache;
      this.getlist();
      // let temparray = [];
      // let array = [];
      // console.log(this.form.inventoryNo);
      // for (let i = 0; i < this.form.inventoryNo.length; i++) {
      //   temparray = this.form.inventoryNo[i].split("|");
      //   array.push(parseInt(temparray[0]));
      //   console.log("arrya========", temparray);
      //   console.log("arrya========", array);
      // }
      // let data =
      //   "?inventoryInformationFileIdList=" +
      //   array +
      //   "&auditMark=" +
      //   form.auditMark +
      //   "&storageUnit=" +
      //   form.pkStordoc +
      //   "&BusinessDateBeginning=" +
      //   this.BusinessDateBeginning() +
      //   "&BusinessDateEnding=" +
      //   this.BusinessDateEnding() +
      //   "&accountingDateBeginning=" +
      //   this.accountingDateBeginning() +
      //   "&accountingDateEnding=" +
      //   this.accountingDateEnding();
      // $http.shuizhangchaxun(data).then((res) => {
      //   this.data = res.result.records;
      //   console.log(res);
      // });
    },
    // 重置
    reset() {
      this.form = {
        inventoryNo: [],
        inventoryName: [],
        BusinessDate: [],
        auditMark: "",
        pkStordoc: "",
        accountingPeriodDate: [],
        inboundOutboundIdentification: "",
        inboundOutboundIdentification_dirtext: "",
      };
      this.queryPathChache = "";
      this.pagination = {
        total: 0,
        current: 1,
        pageSize: 10, //每页中显示10条数据
        pageSizeOptions: ["10"], //每页中显示的数据
        showTotal: (total) => `共有${total}条数据`, //分页中显示总的数据
      };
      this.getlist();
    },
    BusinessDateBeginning() {
      if (this.form.BusinessDate[0]) {
        return `${moment(this.form.BusinessDate[0]).format("YYYY-MM-DD")}`;
      } else {
        return "";
      }
    },
    BusinessDateEnding() {
      if (this.form.BusinessDate[1]) {
        return `${moment(this.form.BusinessDate[1]).format("YYYY-MM-DD")}`;
      } else {
        return "";
      }
    },
    accountingDateBeginning() {
      if (this.form.accountingPeriodDate[0]) {
        return `${moment(this.form.accountingPeriodDate[0]).format(
          "YYYY-MM-DD"
        )}`;
      } else {
        return "";
      }
    },
    accountingDateEnding() {
      if (this.form.accountingPeriodDate[0]) {
        return `${moment(this.form.accountingPeriodDate[0]).format(
          "YYYY-MM-DD"
        )}`;
      } else {
        return "";
      }
    },
    //单据状态
    getAuditMarkAndDocumentStatus() {
      $zidianhttp.getAuditMarkAndDocumentStatus().then((res) => {
        this.danjuzhuangtailist = res.result;
        console.log(this.danjuzhuangtailist);
      });
    },

    getApplyStorage() {
      this.WarehouseCodeList = [];
      // 获取仓库名称
      comHttp.getAllNumberName_new_forU8c().then((res) => {
        console.log("获取所有仓库", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            id: res.result[i].pkStordoc,
            depotName: res.result[i].storname,
            depotNo: res.result[i].storcode,
            pkStordoc: res.result[i].pkStordoc,
          };
          this.WarehouseCodeList.push(data);
        }
        console.log("返回仓库编码、仓库名称", this.WarehouseCodeList);
      });
    },
    //获取列表
    getlist() {
      const { current } = this.pagination; // 分页第一步：拿到要跳转的页数
      let query = `?pageNo=${current}${this.queryPathChache}`;
      $http.getliushuizhang(query).then((res) => {
        console.log("出入库流水账获取列表", res);

        // 分页第二步：将服务七返回的分页数据存储到页面上
        this.pagination.current = res.result.current;
        this.pagination.total = res.result.total;
        this.pagination.pageSize = res.result.size;
        this.maxSize = res.result.total;
        let dataSource = [];
        const data = res.result.records;
        for (let i = 0; i < data.length; i++) {
          let Data = {
            key: i + (current - 1) * res.result.size + 1, // 分页3：修改数据序号
            accountingPeriodDate: data[i].accountingPeriodDate, //会计期间
            BusinessDate: data[i].businessDate, //业务日期
            document: data[i].document, //单据号
            sendReceiveType: data[i].sendReceiveType, //收发类别
            pkStordoc: data[i].storname, //仓库名称
            inventoryNo: data[i].invcode, //存货编码
            inventoryName: data[i].invname, //存货名称
            specificationsModel: data[i].invspec, //规格型号
            unit: data[i].measname, //计量单位
            ruunitPrice: data[i].inUnitPrice, //入库单价
            ruquantity: data[i].inQuantity, //入库数量
            rumoney: data[i].inMoney, //入库金额
            chuunitPrice: data[i].outUnitPrice, //出库单价
            chumoney: data[i].outMoney, //出库数量
            chuquantity: data[i].outQuantity,
            clientId: data[i].customerName, //客户
            supplier: data[i].supplier, //供应商
            sourceNumber:
              data[i].sourceNumber == "null" ? "" : data[i].sourceNumber, //源单号
            finishedProductType: data[i].finishedProductType_dictText, //产成品分类
            finishedProductDepot: data[i].finishedProductDepot_dictText, //产成品仓库
            remark: data[i].remark, //备注
            singleProducer: data[i].singleProducer_dictText, //制单人
            inspector: data[i].inspector_dictText, //审核人
          };
          dataSource.push(Data);
        }
        this.dataSource = dataSource;
        if (this.dataSource == undefined || this.dataSource.length <= 0) {
          this.$message.warning("暂无符合查询条件的数据");
        }
        // this.$message.info("This is a normal message");
      });
    },
    // 分页4：拿到组件跳转的页数
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.getlist();
    },
  },
};
</script>

